from fastapi import APIRouter, Depends
import sympy
import math
from pydantic import BaseModel

from backend.app.app.api.api_v1.user import verify_token_user
from backend.app.app.crud_pro.tb_userpro_input import get_name_year, get_query_data, get_query_data_by_id, get_name_year_public
from backend.app.app.crud_pro.tb_userpro_base import copy_page
from backend.app.app.models.dvpunithist import data, data1, data_save, data_query, data_page
from backend.app.app.api.calculation.evaluation_calculation import calculation_critical_value
from backend.app.app.crud_pub.tb_profit_analysis import query_data, get_p_id, get_u_id, updata_project_db, get_p_id_u

dvpunithist_router = APIRouter(prefix="/dvpunithist", tags=["历史单元盈亏平衡分析"])


@dvpunithist_router.post("save_as", name="另存为,pro_id给任意值")
async def save_as(data: data_save, ver=Depends(verify_token_user)):
    #   存当前页面数据
    old_p_id = data.Proj_ID
    p_id = get_p_id_u(user_id=data.User_ID)
    pid = []
    for i in p_id:
        pid.append(int(i[0]))
    pid.sort()
    new = 0
    for j in range(1, len(pid)):
        if (pid[j] - pid[j - 1]) != 1:
            new = pid[j - 1] + 1
    if new == 0:
        new = pid[j] + 1
    data.Proj_ID = str(new)
    re = updata_project_db(s_data=data)

    #   复制其他页面数据
    a, b, c = copy_page(old_user_id=data.User_ID,
                        old_pro_id=old_p_id, new_pro_id=str(new))
    return {"result_current_page": re, "page1": a,
            "page2": b, "page3": c, "verify": ver}


@dvpunithist_router.post("/read_data", name="读取页面数据，临界值，盈亏结果，敏感参数")  #
async def read_data(trans_data: data_page, ver=Depends(verify_token_user)):
    result = query_data(user_Id=trans_data.user_id, Pro_Id=trans_data.project_id)
    return {"result": result, "verify": ver}


@dvpunithist_router.post("/save_data", name="保存页面数据，临界值，盈亏结果")  #
async def save_data(input_data: data_save, ver=Depends(verify_token_user)):
    result = updata_project_db(input_data)
    return {"result": result, "verify": ver}


@dvpunithist_router.post("/analysis_calculation", name="分析盈亏计算")
async def analysis_calculation(trans_data: data1, ver=Depends(verify_token_user)):
    StimNPV = []
    pa = trans_data.parameter_set
    ValidYears = math.ceil(trans_data.Stim_ValidPeriod_Average / 365)
    IncreOilPy = trans_data.Stim_IncreOil_Average / ValidYears
    ic = trans_data.Money_Discount / 100
    re = 0
    for k in range(1, ValidYears + 1):
        re += (1 - ic) ** k
    for i in pa:
        StaticGainsPy = IncreOilPy * (i * trans_data.StimOil_CommodityRatio / 100 * (
            1 - trans_data.OilSale_TotalTaxRatio / 100) - trans_data.Oil_OprCost)

        temp = re * StaticGainsPy - trans_data.StimCost_Average
        temp.__float__()
        StimNPV.append(temp)

    return {"StimNPV": StimNPV, "verify": ver}


@dvpunithist_router.post("/calculation_critical_value_oilprice",
                         name="计算敏感参数-油价")
async def cal_cri_value_oilpricd(trans_data: data, ver=Depends(verify_token_user)):
    value_stimcost = None
    value_increoil = None
    value_oilprice = None
    a = calculation_critical_value.set_data(
        calculation_critical_value, trans_data)
    if a:
        value_stimcost = calculation_critical_value.stimcost_critical_value(
            calculation_critical_value)  # 临界作业成本
        value_increoil = calculation_critical_value.increoil_critical_value(
            calculation_critical_value)  # 临界措施增油
        value_oilprice = calculation_critical_value.oil_critical_value(
            calculation_critical_value)  # 临界油价

    OilPrice: float = trans_data.Oil_Price

    parm = []
    if OilPrice > value_oilprice:
        PriceStep = 100 * math.ceil(value_oilprice / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k

            parm.append(OilPriceSensi_k)
        PriceStep = 100 * math.ceil((OilPrice * 1.2 - value_oilprice) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            parm.append(OilPriceSensi_k)
    else:
        PriceStep = 100 * math.ceil(value_oilprice / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            parm.append(OilPriceSensi_k)
        PriceStep = 100 * math.ceil((value_oilprice * 1.5 - OilPrice) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            parm.append(OilPriceSensi_k)
    print(parm)
    print(type(parm))
    re_parm = []
    for i in parm:
        a = sympy.core.numbers.Integer.__int__(i)
        re_parm.append(a)

    value_oilprice = str(value_oilprice)
    value_increoil = str(value_increoil)

    return {"value_stimcost": value_stimcost, "value_increoil": value_increoil,
            "value_oilprice": value_oilprice, "parameter_set": re_parm, "verify": ver}  # ,"verify":ver


@dvpunithist_router.post("/calculation_critical_value_increoil",
                         name="计算敏感参数-措施增油")
async def cal_cri_value_increoil(trans_data: data, ver=Depends(verify_token_user)):  #
    value_stimcost = None
    value_increoil = None
    value_oilprice = None
    a = calculation_critical_value.set_data(
        calculation_critical_value, trans_data)
    if a:
        value_stimcost = calculation_critical_value.stimcost_critical_value(
            calculation_critical_value)  # 临界作业成本
        value_increoil = calculation_critical_value.increoil_critical_value(
            calculation_critical_value)  # 临界措施增油
        value_oilprice = calculation_critical_value.oil_critical_value(
            calculation_critical_value)  # 临界油价

    IncreOil: float = trans_data.Stim_IncreOil_Average

    parm = []
    if IncreOil > value_increoil:
        PriceStep = 100 * math.ceil(value_increoil / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 100 * math.ceil((IncreOil * 1.2 - value_increoil) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)
    else:
        PriceStep = 100 * math.ceil(value_increoil / 1000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 100 * math.ceil((value_increoil * 1.5 - IncreOil) / 1000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)

    value_oilprice = str(value_oilprice)
    value_increoil = str(value_increoil)
    return {"value_stimcost": value_stimcost, "value_increoil": value_increoil,
            "value_oilprice": value_oilprice, "parameter_set": parm, "verify": ver}


@dvpunithist_router.post("/calculation_critical_value_stimcost",
                         name="计算敏感参数-作业成本")
async def cal_cri_value_stimcost(trans_data: data, ver=Depends(verify_token_user)):
    value_stimcost = None
    value_increoil = None
    value_oilprice = None
    a = calculation_critical_value.set_data(
        calculation_critical_value, trans_data)
    if a:
        value_stimcost = calculation_critical_value.stimcost_critical_value(
            calculation_critical_value)  # 临界作业成本   ,ver = Depends(verify_token_user)
        value_increoil = calculation_critical_value.increoil_critical_value(
            calculation_critical_value)  # 临界措施增油
        value_oilprice = calculation_critical_value.oil_critical_value(
            calculation_critical_value)  # 临界油价

    Stimcost: float = trans_data.StimCost_Average

    parm = []
    if Stimcost > value_stimcost:
        PriceStep = 10000 * math.ceil(value_stimcost / 100000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 10000 * \
            math.ceil((Stimcost * 1.2 - value_stimcost) / 100000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)
    else:
        PriceStep = 10000 * math.ceil(value_stimcost / 100000)
        for k in range(1, 11):
            OilPriceSensi_k = PriceStep * k
            a = OilPriceSensi_k.__int__()
            parm.append(a)
        PriceStep = 10000 * \
            math.ceil((value_stimcost * 1.5 - Stimcost) / 100000)
        for k in range(11, 21):
            OilPriceSensi_k = parm[9] + PriceStep * (k - 10)
            a = OilPriceSensi_k.__int__()
            parm.append(a)

    value_oilprice = str(value_oilprice)
    value_increoil = str(value_increoil)
    return {"value_stimcost": value_stimcost, "value_increoil": value_increoil, "value_oilprice": value_oilprice,
            "parameter_set": parm, "verify": ver}


@dvpunithist_router.post("/read_lib", name="读库")
async def read_lib(input_data: data_query, ver=Depends(verify_token_user)):
    data = get_query_data(
        dvpUnit_Name=input_data.name,
        stimType_Name=input_data.type,
        year=input_data.year)

    return {"data": data, "verify": ver}


@dvpunithist_router.post("/get_name_type_year", name="获取单元名称，措施类别，年度")
async def get_name_type_year(ver=Depends(verify_token_user)):
    data = get_name_year_public()
    return {'data':data,"verify":ver}
